<script setup lang="ts">
import {uploadPictureProps} from "./uploadPicture";
import {ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import {useVModel} from "@vueuse/core";
import {ElMessage} from "element-plus";
import {deleteFileUrl, uploadFileUrl} from "@/api/file/index.js";

defineOptions({
  name: 'UploadPictureFiles',
})

const props = defineProps(uploadPictureProps)
const $emit = defineEmits([""])
const modelValue = useVModel(props, 'fileData', $emit)
const fileList = useVModel(props, 'fileData', $emit)
const newFile = ref(null)
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imgPreviewList = ref([])
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
  imgPreviewList.value = [uploadFile.url]
}
// 超出文件上传个数
const onExceed = (file, fileList) => {
  ElMessage.error('文件上传个数已达上限!')
}

const closePreview = () => {
  imgPreviewList.value = []
  dialogVisible.value = false
}

// 文件上传前的钩子函数
const beforeUpload = (rawFile) => {
  newFile.value = rawFile;
}

const upload = () => {
  const rawFile = newFile.value; //  3. 拿到刚刚的数据，并将其传给后台
  // 上传图片
  let param = new FormData(); // 创建form对象
  param.append("files", rawFile, rawFile.name); // 通过append向form对象添加数据
  return new Promise((resolve, reject) => {
    uploadFileUrl(props.uploadUrl, param).then((req: any) => {
      ElMessage.success(req.msg)
      resolve(req)
    })
        .catch(err => {
          console.log(err)
          reject(new Error("上传失败!"))
        })
  })
}

// 文件被删除前的回调函数
const beforeRemove = (uploadFile, uploadFiles) => {
  console.log("uploadFile", uploadFile, uploadFiles)
  if (!uploadFile || uploadFile.status !== 'success') return
  return new Promise((resolve, reject) => {
    // 删除文件
    deleteFileUrl(uploadFile.fileId).then((res: any) => {
      // 将对应的文件移除
      modelValue.value.fileList = modelValue.value.fileList.filter(item => item.uid !== uploadFile.uid)
      ElMessage.success(res.msg)
      resolve(true)
    }).catch(err => {
      console.log(err)
      reject(new Error("删除失败!"))
    })
  })
}

const handleRemove = (file) => {
  console.log("handleRemove", file)
  if (!file || file.status !== 'success') return
  return new Promise((resolve, reject) => {
    // 删除文件
    deleteFileUrl(file.fileId).then((res: any) => {
      // 将对应的文件移除
      fileList.value = fileList.value.filter(item => item.fileId !== file.fileId)
      ElMessage.success(res.msg)
      resolve(true)
    }).catch(err => {
      console.log(err)
      reject(new Error("删除失败!"))
    })
  })
}


/**
 *  文件上传成功后的回调函数
 * @param res 上传成功后返回的信息
 * @param file
 * @param _fileList
 */
const onSuccess = (res, file, _fileList) => {
  console.log("file", res)
  console.log("file", file)
  console.log("file", _fileList)
  const resultList = res.data[0]
  // 将 res 的结果输入进去
  fileList.value = fileList.value.map((item) => {
    if (item.uid === file.uid) {
      return {
        fileId: resultList.id,
        fileName: res.target,
        srcFileName: resultList.name,
        ...item,
      }
    }else {
      return item
    }
  })
  // fileList.value = modelValue.value.fileList.map((item) => {
  //   if (item.uid === file.uid) {
  //     return {
  //       fileId: res.id,
  //       fileName: res.target,
  //       srcFileName: res.filename,
  //       ...item,
  //     }
  //   } else {
  //     return item
  //   }
  // })
}

const handleDownload = (file) => {
  if (!file || file.status !== 'success') return
  // downloadReal(file.fileId, file.fileName, file.srcFileName)
}

</script>

<template>
  <el-upload
      action=""
      :accept="props.fileType"
      :disabled="props.disabled"
      v-model:file-list="fileList"
      list-type="picture-card"
      :multiple="true"
      :before-upload="beforeUpload"
      :before-remove="beforeRemove"
      :on-success="onSuccess"
      :http-request="upload"
      :limit="props.maxFileNum"
      :on-exceed="onExceed"
      :on-preview="handlePictureCardPreview"
  >
    <el-icon>
      <Plus/>
    </el-icon>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt=""/>
        <div v-if="file.status === 'success'" class="upload-status-checkmark">
          <i class="el-icon-check">
            <el-icon>
              <Check/>
            </el-icon>
          </i>
        </div>
        <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in/></el-icon>
          </span>
          <span
              class="el-upload-list__item-delete"
              @click="handleDownload(file)"
          >
            <el-icon><Download/></el-icon>
          </span>
          <span
              v-if="!props.disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <el-icon><Delete/></el-icon>
          </span>
        </span>
      </div>
    </template>
    <template #tip>
      <!--      <p>注意: 已经上传了 {{ modelValue.fileList == null ? 0 : modelValue.fileList.length }} 张照片, 图片上传数量在{{props.minFileNum}}~{{props.maxFileNum}} 之间</p>-->
    </template>
  </el-upload>

  <!-- 图片预览 -->
  <el-image-viewer
      v-if="dialogVisible"
      @close="closePreview"
      :url-list="imgPreviewList"
  />
</template>

<style scoped lang="scss">
.upload-status-checkmark {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-top: 30px solid #67c23a; /* 大小根据需要调整，创建三角形 */
  border-left: 30px solid transparent; /* 创建半透明边框 */
  border-bottom: 0;
  border-right: 0;
  /* 额外的样式以确保三角形的位置和形状 */
}

.upload-status-checkmark .el-icon-check {
  position: absolute;
  top: -28px; /* 根据三角形大小调整 */
  right: -1px; /* 根据三角形大小调整 */
  color: white;
  font-size: 16px; /* 根据需要调整大小 */
  /* 旋转对勾图标以适应三角形的形状 */
  //transform: rotate(-45deg);
}
</style>
